import random
import re
from homodecipher import HomoDecipher
from ngram_score import ngram_score
import string

class Breakhomophonic:
    def __init__(self):
        self.fitness = ngram_score('bigram.txt') # load our quadgram statistics
        self.fitness1 = ngram_score('english_trigrams.txt')
        self.fitness2 = ngram_score('english_quadgrams.txt')
        ##ctext='643265654220642581201888932068579104203349200218801320347420651070042081277630208748412216204985223104203520185120995375682070862300203042205132533020688591042054452068429120277699132016277120633651132024523240030296042012657155745220791365402033530420278720646204201014203417207620965711662005556820164220126519492048188967007997366540'
        
        
        
        alphabets = string.ascii_lowercase
        
        
        self.values = list()
        for i in range(0,100):
            if i < 10:
                self.values.append('0'+str(i))
            else:
                self.values.append(str(i))
                
        for i in alphabets:
            self.values.append(str(i))
            
        self.values.append(' ')
        self.values.append('!')
        self.values.append('?')
        self.values.append(',')
        self.values.append('.')
        
        ##print self.values
        ##print len(self.values)
        
          
        self.maxscore = -999999999999999999999999
        self.parentscore,self.parentkey = self.maxscore,self.values[:]
    
    def crack_string(self,ctext):
        c = HomoDecipher()
        i = 0
        while i <= 100000:   ## at most 10000 key combination, if more than this, we won't decipher it any more
            random.shuffle(self.values)   ##shuffle to generate random keys
            i = i + 1
            realtext = c.getkey(self.values,ctext)
            self.parentscore = self.fitness.score(realtext)+self.fitness1.score(realtext)+self.fitness2.score(realtext)
           
            ##print str(parentscore) + ','
            ##print parentscore
            if self.parentscore > self.maxscore:
                self.maxscore = self.parentscore
                print 'iteration: ' + str(i)
                print 'Score is: ' +str(self.parentscore)
                print 'text is: ' + realtext
                mtext = realtext
        print 'done'
        return mtext
                ##print realtext
       
            
        

























